import React, { useEffect, useState } from 'react';
import { ModalForm, PageContainer, ProColumns, ProFormText, ProTable, ProForm } from '@ant-design/pro-components';
import { Category } from '@/types/business';
import { request } from '@umijs/max';
import { Button } from 'antd';
import { PlusOutlined } from '@ant-design/icons';
import SubEditDrawer from '@/pages/Category/components/SubEditDrawer';


function getTopCategory() {
  return request('/admin/goods/getCategoryTree', {
    method: 'post',
  });
}


export default function CategoryPage() {
  const [dataSource, setDataSource] = useState<Category[]>([]);
  const [visible, setVisible] = useState(false);
  const [drawerId, setDrawerId] = useState<number | undefined>(undefined);
  const [form] = ProForm.useForm();

  const openDrawer = (id: number | undefined) => {
    if(!id) return;
    setDrawerId(id)
    setVisible(true);
  }

  const columns: ProColumns<Category>[] = [
    {
      title: 'ID',
      dataIndex: 'id',
      valueType: 'index',
      width: 48,
    },
    {
      title: '分类名称',
      dataIndex: 'categoryName',
    },
    {
      title: '子类数量',
      render: (_, entity) => {
        if(!entity?.children) return 0;
        return entity?.children.length
      },
    },
    {
      title: '操作',
      valueType: 'option',
      fixed: 'right',
      render: (_dom, entity) => [
        <a key={'sub-edit-'+ entity.id} onClick={() => openDrawer(entity.id)}>二级目录编辑</a>,
        <ModalForm
          key={'editModal'}
          title={'编辑分类'}
          form={form}
          onOpenChange={(open) => {
            if(open) {
              form.setFieldsValue(entity)
            }
          }}
          onFinish={async (values) => {
            console.log(values, entity);
            Object.assign(values, {
              id: entity.id
            })
            const data = await request('/admin/goods/saveOrUpdateCategory', {
              method: 'post',
              data: values
            })
            if(data.data) {
              getTopCategory().then((res) => {
                setDataSource(res.data);
              });
              return true
            }
          }}
          trigger={
            <a key={`edit-${entity.id}`}>编辑</a>
          }
        >
            <ProForm.Group>
              <ProFormText
                width="md"
                name="categoryName"
                label="分类名称"
                tooltip="最长为 8 位"
                placeholder="请输入分类名称"
              />
            </ProForm.Group>
        </ModalForm>,
        <a key={`delete-${entity.id}`}>删除</a>,
      ],
    },
  ];

  useEffect(() => {
    getTopCategory().then((res) => {
      setDataSource(res.data);
    });
  }, []);
  return (
    <>
      <PageContainer
        title={'目录管理'}
      >
        <ProTable
          rowKey={"id"}
          columns={columns}
          search={false}
          dataSource={dataSource}
          expandable={{
            childrenColumnName: 'child'
          }}
          request={async () => {
            const data = await getTopCategory();
            return {
              data: data.data,
              success: true,
            }
          }}
          toolBarRender={() => [
            <ModalForm
              key={'addModal'}
              title={'新建分类'}
              trigger={
                <Button type="primary">
                  <PlusOutlined />
                  新建分类
                </Button>
              }
            >
              <ProForm.Group>
                <ProFormText
                  width="md"
                  name="categoryName"
                  label="分类名称"
                  tooltip="最长为 8 位"
                  placeholder="请输入分类名称"
                />
              </ProForm.Group>
            </ModalForm>
          ]}
        ></ProTable>
      </PageContainer>

      {/* 二级分类编辑 */}
      <SubEditDrawer
        visible={visible}
        setVisible={setVisible}
        id={drawerId}
      ></SubEditDrawer>
    </>
  );
}
